<template>
  <div>
    <van-nav-bar title="购物车" left-text="返回" />
    <div class="list">
      <div class="item" v-for="(item,index) in cartList" :key="index">
        <van-checkbox class="inp" v-model="item.checked" />
        <van-card :title="item.name" :thumb="item.img" :price="item.price" class="card">
          <template #num>
            <van-stepper v-model="item.nums" />
          </template>
        </van-card>
        <button class="shan" @click="del(index)">编辑</button>
      </div>
    </div>
    <input type="checkbox" :checked="allCheck" @click="quan"> 全选</input>
    <van-submit-bar :price="tonums" button-text="提交订单" style="bottom:1rem;">
      <!-- <van-checkbox :checked="allCheck" @click="quan">全选</van-checkbox> -->
    </van-submit-bar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cartList: [],
      // checked: true,
      allCheck: false,
    };
  },
  created() {},
  computed: {
    tonums() {
      //数据的提交
      if (this.cartList.length > 0) {
        this.$store.commit("addCart", this.cartList);
      }
      let amounts = 0;
      this.cartList.forEach((item) => {
        if (item.checked == true) {
          amounts += item.nums * item.price;
        }
      });
      return amounts * 100;
    },
  },
  watch: {
    cartList: {
      // handler(value) {
      //   this.$store.commit("addCart", value);
      //   this.$store.commit("tonums");

      //   let arr = value.filter((item) => {
      //     return item.checked == true;
      //   });
      //   if (value.length == arr.length) {
      //     this.checked = true;
      //   } else {
      //     this.checked = false;
      //   }
      // },
      handler(val) {
        this.allCheck = this.cartList.every((item) => {
          return item.checked;
        });
      },
      deep: true,
    },
  },
  mounted() {
    this.cartList = this.$store.state.cartList;
  },
  methods: {
    del(index) {
      this.cartList.splice(index, 1);
    },
    quan() {
      // this.cartList.map(item=>{
      //   item.checked = e

      // })
      //先取反
      this.allCheck = !this.allCheck;
      this.cartList.forEach((item) => {
        item.checked = this.allCheck;
      });
    },
  },
};
</script>

<style scoped lang="less">
.list {
  width: 100%;
  .item {
    padding: 0.1rem;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    align-items: center;
    .inp {
      width: 15%;
    }
    .card {
      flex: 1;
    }
  }
}
.shan {
  font-size: 0.14rem;
}
</style>






